package de.idgard.android.addon.ui.services.impl;

import java.net.URL;
import java.util.List;

import android.os.AsyncTask;

import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndEntry;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndFeed;
import com.google.code.rome.android.repackaged.com.sun.syndication.io.SyndFeedInput;
import com.google.code.rome.android.repackaged.com.sun.syndication.io.XmlReader;

import de.idgard.android.R;
import de.idgard.android.addon.services.GlobalServiceRegistry;
import de.idgard.android.addon.ui.services.NewsService;
import de.idgard.json.transport.AbstractAsyncRequest;
import de.idgard.json.transport.AsyncRequest;
import de.idgard.json.transport.Receiver;

/**
 * 
 * @author <a href="mailto:vesko.georgiev@uniscon.com">Vesko Georgiev</a>
 */
public class NewsServiceImpl implements NewsService {

	@Override
	@SuppressWarnings("unchecked")
	public AsyncRequest<SyndEntry> getLatestNews() {
		return new AbstractAsyncRequest<SyndEntry>() {
			private Exception exception;
			@Override
			public void fire(final Receiver<SyndEntry> receiver) {
				new AsyncTask<Void, Void, SyndEntry>() {
					@Override
					protected SyndEntry doInBackground(Void... params) {
						try {
							URL feedSource = new URL(GlobalServiceRegistry.instance().getPropertiesService().getString(R.string.idgard_news_rss_url));
							SyndFeedInput input = new SyndFeedInput();
							SyndFeed feed = input.build(new XmlReader(feedSource));

							List<SyndEntry> entries = feed.getEntries();

							return entries.get(0);
						}
						catch (Exception e) {
							exception = e;
							e.printStackTrace(); 
						}
						return null;
					}

					@Override
					protected void onPostExecute(SyndEntry result) {
						if (result != null) {
							receiver.onSuccess(result);
						}
						else if (exception != null) {
							receiver.onException(exception);
						}
						else {
							receiver.onFailure(0, "Unknown Error");
						}
					}
				}.execute();
			}
		};
	}

}
